package euler.p001_050;

import euler.MainEuler;

public class Euler037 extends MainEuler {
    /*
        The number 3797 has an interesting property.
        Being prime itself, it is possible to continuously
        remove digits from left to right, and remain prime
        at each stage: 3797, 797, 97, and 7.
        Similarly we can work from right to left:
        3797, 379, 37, and 3.

        Find the sum of the only eleven primes that are
        both truncatable from left to right and right to left.

        NOTE: 2, 3, 5, and 7 are not considered to
        be truncatable primes.

     */
    public String resolve() {

        int suma = 0;

        for (int i = 23, count = 0; count < 11; i+=2) {
            if (truncatableRight2Left(i) && truncatableLeft2Right(i)) {
                count++;
                suma+=i;
            }
        }

        return String.valueOf(suma);
    }

    private boolean truncatableLeft2Right(int n) {

        if (n < 2) {
            return false;
        }

        if (!primeHelper.isPrime(n)) {
            return false;
        }

        if (n < 10) {
            return true;
        }

        int digitos = (int)(Math.log10(n));
        int p = (int)Math.pow(10, digitos);
        int digito = ((n % (p*10)) - (n % p))/p;

        return truncatableLeft2Right(n - digito * (int)Math.pow(10, digitos));
    }

    private boolean truncatableRight2Left(int n) {

        if (n < 2) {
            return false;
        }

        if (!primeHelper.isPrime(n)) {
            return false;
        }

        if (n < 10) {
            return true;
        }

        return truncatableRight2Left((int)n/10);
    }

}
